<?php


namespace app\common\library;


use think\facade\Cache;
use think\facade\Request;

class TokenManager
{
    private $module;

    /**
     * TokenManager constructor.
     * @param string|null $module 模块名，留空则自动识别
     */
    public function __construct(string $module = null)
    {
        if (is_null($module)) {
            $this->module = Request::module();
        }
    }


    /**
     * 创建令牌
     * @param string $key
     * @param int $expire_in
     * @return string
     */
    public function create(string $key, int $expire_in = 86400): string
    {
        $str = dechex(Request::ip(true));
        $str .= $key;
        $str .= mt_rand(0, 9999999);
        $str .= $_SERVER['REQUEST_TIME'];

        $token = md5($str);
        Cache::set($this->module . ':' . $key, $token, $expire_in);

        return $token;
    }


    /**
     * 令牌是否存在
     * @param string $key
     * @return bool
     */
    public function exist(string $key): bool
    {
        return Cache::has($this->module . ':' . $key);
    }


    /**
     * 清除令牌
     * @param string $key
     */
    public function delete(string $key): void
    {
        Cache::rm($this->module . ':' . $key);
    }
}
